<!--
  智慧社区管理系统 - 投诉建议处理流程页面
  @author Wu.Liang
  @date 2025-01-27
-->
<template>
  <div class="complaint-process-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">投诉处理流程</h2>
      <div class="page-actions">
        <el-button @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
        <el-button type="primary" @click="handleProcess" :loading="processing">
          <el-icon><Check /></el-icon>
          处理投诉
        </el-button>
      </div>
    </div>

    <!-- 投诉详情 -->
    <el-card class="detail-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>投诉详情</span>
          <el-tag :type="getTagType(getStatusTagType(complaintDetail.status))">
            {{ getStatusText(complaintDetail.status) }}
          </el-tag>
        </div>
      </template>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="投诉编号">{{ complaintDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="投诉标题">{{ complaintDetail.title }}</el-descriptions-item>
        <el-descriptions-item label="投诉分类">{{ complaintDetail.categoryName }}</el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag :type="getTagType(getPriorityTagType(complaintDetail.priority))">
            {{ getPriorityText(complaintDetail.priority) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="投诉人">{{ complaintDetail.userName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ complaintDetail.userPhone }}</el-descriptions-item>
        <el-descriptions-item label="所属社区">{{ complaintDetail.communityName }}</el-descriptions-item>
        <el-descriptions-item label="房户信息">{{ complaintDetail.householdInfo }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ formatDateTime(complaintDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="预计解决时间">
          {{ complaintDetail.estimatedResolveTime ? formatDateTime(complaintDetail.estimatedResolveTime) : '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="投诉内容" :span="2">
          <div class="content-text">{{ complaintDetail.content }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 处理流程 -->
    <el-card class="process-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>处理流程</span>
          <el-button type="primary" size="small" @click="handleAddProcess">
            <el-icon><Plus /></el-icon>
            添加处理记录
          </el-button>
        </div>
      </template>
      
      <el-timeline>
        <el-timeline-item
          v-for="(process, index) in processList"
          :key="process.id"
          :timestamp="formatDateTime(process.createTime)"
          :type="getTimelineItemType(process.status)"
        >
          <el-card class="process-item">
            <div class="process-header">
              <span class="process-action">{{ process.actionName }}</span>
              <el-tag :type="getTagType(getStatusTagType(process.status))" size="small">
                {{ process.statusName }}
              </el-tag>
            </div>
            <div class="process-content">{{ process.content }}</div>
            <div class="process-footer">
              <span class="process-operator">处理人：{{ process.operatorName }}</span>
              <span v-if="process.remark" class="process-remark">备注：{{ process.remark }}</span>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 处理表单弹窗 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理投诉"
      width="600px"
      :before-close="handleCloseProcessDialog"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processFormRules"
        label-width="100px"
      >
        <el-form-item label="处理动作" prop="action">
          <el-select v-model="processForm.action" placeholder="请选择处理动作" style="width: 100%">
            <el-option label="接收投诉" value="RECEIVE" />
            <el-option label="联系投诉人" value="CONTACT" />
            <el-option label="现场调查" value="INVESTIGATE" />
            <el-option label="制定方案" value="PLAN" />
            <el-option label="执行处理" value="EXECUTE" />
            <el-option label="回访确认" value="FOLLOWUP" />
            <el-option label="关闭投诉" value="CLOSE" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="processForm.status" placeholder="请选择处理状态" style="width: 100%">
            <el-option label="待处理" :value="0" />
            <el-option label="处理中" :value="1" />
            <el-option label="已解决" :value="2" />
            <el-option label="已关闭" :value="3" />
            <el-option label="已驳回" :value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="处理内容" prop="content">
          <el-input
            v-model="processForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述处理过程和结果..."
          />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息..."
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseProcessDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmitProcess" :loading="processing">
            确认处理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showError, showSuccess } from '@/utils/message'
import { 
  Plus, 
  Check, 
  ArrowLeft
} from '@element-plus/icons-vue'
import type { Complaint, ComplaintProcess, ProcessComplaintParams } from './types/complaint'
import { complaintApi, complaintProcessApi } from '@/api/complaint'
import { getTagType } from '@/utils/message'

// 作者: Wu.Liang

// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const processing = ref(false)
const processDialogVisible = ref(false)
const processFormRef = ref()

// 投诉详情
const complaintDetail = ref<Complaint>({} as Complaint)

// 处理流程列表
const processList = ref<ComplaintProcess[]>([])

// 处理表单
const processForm = reactive<ProcessComplaintParams>({
  action: '',
  content: '',
  status: 1,
  remark: ''
})

// 表单验证规则
const processFormRules = {
  action: [
    { required: true, message: '请选择处理动作', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择处理状态', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入处理内容', trigger: 'blur' },
    { min: 5, max: 500, message: '内容长度在 5 到 500 个字符', trigger: 'blur' }
  ]
}

// 生命周期
onMounted(() => {
  const complaintId = route.params.id
  if (complaintId) {
    loadComplaintDetail(Number(complaintId))
    loadProcessList(Number(complaintId))
  }
})

// 加载投诉详情
const loadComplaintDetail = async (complaintId: number) => {
  try {
    const response = await complaintApi.getComplaintDetail(complaintId)
    if (response.code === 200) {
      complaintDetail.value = response.data
    }
  } catch (error) {
    console.error('加载投诉详情失败:', error)
    showError('加载投诉详情失败')
  }
}

// 加载处理流程
const loadProcessList = async (complaintId: number) => {
  try {
    const response = await complaintProcessApi.getProcessList(complaintId)
    if (response.code === 200) {
      processList.value = response.data
    }
  } catch (error) {
    console.error('加载处理流程失败:', error)
    showError('加载处理流程失败')
  }
}

// 事件处理
const handleBack = () => {
  router.push('/complaint/list')
}

const handleProcess = () => {
  processDialogVisible.value = true
}

const handleAddProcess = () => {
  processDialogVisible.value = true
}

const handleCloseProcessDialog = () => {
  processDialogVisible.value = false
  processFormRef.value?.resetFields()
}

const handleSubmitProcess = async () => {
  try {
    await processFormRef.value.validate()
    
    processing.value = true
    const complaintId = Number(route.params.id)
    
    const response = await complaintApi.processComplaint(complaintId, processForm)
    if (response.code === 200) {
      showSuccess('处理成功')
      handleCloseProcessDialog()
      loadProcessList(complaintId)
      loadComplaintDetail(complaintId)
    } else {
      showError(response.message || '处理失败')
    }
  } catch (error) {
    console.error('处理失败:', error)
    showError('处理失败')
  } finally {
    processing.value = false
  }
}

// 工具方法
const getStatusTagType = (status: number) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return typeMap[status as keyof typeof typeMap] || 'info'
}

const getStatusText = (status: number) => {
  const textMap = {
    0: '待处理',
    1: '处理中',
    2: '已解决',
    3: '已关闭',
    4: '已驳回'
  }
  return textMap[status as keyof typeof textMap] || '未知'
}

const getPriorityTagType = (priority: number) => {
  const typeMap = {
    1: 'info',
    2: 'success',
    3: 'warning',
    4: 'danger'
  }
  return typeMap[priority as keyof typeof typeMap] || 'info'
}

const getPriorityText = (priority: number) => {
  const textMap = {
    1: '低',
    2: '普通',
    3: '高',
    4: '紧急'
  }
  return textMap[priority as keyof typeof textMap] || '未知'
}

const getTimelineItemType = (status: number) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return typeMap[status as keyof typeof typeMap] || 'info'
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}
</script>

<style scoped>
.complaint-process-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.detail-card,
.process-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-text {
  white-space: pre-wrap;
  line-height: 1.6;
}

.process-item {
  margin-bottom: 10px;
}

.process-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.process-action {
  font-weight: 600;
  color: #303133;
}

.process-content {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #606266;
}

.process-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.process-operator {
  font-weight: 500;
}

.process-remark {
  font-style: italic;
}
</style> 